package com.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.conf.RestTemplateConf;
import com.example.pojo.FastgptVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class AccessToFastGpt {
    @Autowired
    private RestTemplate restTemplateConf;
    @Value("${fastgpt.url}")
    private String FastGptUrl;
    /**
     * Params:
     * Content：问题
     * Key：对话key
     * Stream：是否流式返回
     * Detail：是否返回中间值（模块状态，响应的完整结果等
     */
    public FastgptVO getAccess(String Content, String Key, Boolean Stream, Boolean Detail)
    {
        // 构建请求体
        JSONObject json = new JSONObject();
        try {
            json.put("stream", Stream);
            json.put("detail", Detail);

            JSONArray messages = new JSONArray();
            JSONObject messageDetail = new JSONObject();
            messageDetail.put("role", "user");
            messageDetail.put("content", Content);
            messages.add(messageDetail);

            json.put("messages", messages);
        } catch (Exception e) {
            throw new RuntimeException("构建JSON失败: " + e.getMessage(), e);
        }
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + Key);

        // 构建请求实体
        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);
        log.info("fastgpt请求开始,请求url: " + FastGptUrl + "\n请求key: " + Key + "\n请求体：" + json);
        // 发送请求
        ResponseEntity<String> response;
        try {
            response = restTemplateConf.exchange(
                    FastGptUrl,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
        } catch (Exception e) {
            log.error("请求失败: " + e.getMessage());
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }

        // 输出响应
        log.info("响应结果: " + response.getBody());
        String body = response.getBody();
        com.alibaba.fastjson.JSONObject rsJson = JSON.parseObject(body);
        FastgptVO fastgptVO = new FastgptVO();
        fastgptVO.setId(rsJson.getString("id"));
        fastgptVO.setContent(rsJson.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content"));
        return fastgptVO;
    }
}
